<template>
  <ul class="list">
    <li
      class="item"
      v-for="item in letters"
      :key="item"
      :ref="item"
      @click="handleLetterClick"
      @touchstart.prevent="handleTouchStart"
      @touchmove="handleTouchMove"
      @touchend="handleTouchEnd"
    >
      {{ item }}
    </li>
  </ul>
</template>

<script>
import { cities } from "./data.js";
export default {
  name: "CityAlphabet",
  props: {
    // cities: Object,
  },
  data() {
    return {
      touchStatus: false,
      startY: 0,
      timer: null,
      cities: cities,
    };
  },
  updated() {
    // 字母A距离顶部的距离，startY都是距离绿色的下沿
    this.startY = this.$refs["A"][0].offsetTop;
  },
  computed: {
    // ABCD 首字母
    letters() {
      const letters = [];
      for (let i in this.cities) {
        letters.push(i);
      }
      return letters;
      // [a,b,c,d.......]
    },
  },
  methods: {
    // 兄弟组件传值，先传给父组件，父组件再传给另一个兄弟
    handleLetterClick(e) {
      this.$emit("change", e.target.innerText); // A B C D
    },
    handleTouchStart() {
      this.touchStatus = true;
    },
    handleTouchMove(e) {
      // 思路就是获取A到顶部的高度，滑到B的时候让B的高度减去A 的高度就知道那个字母
      if (this.touchStatus) {
        // 当上下可以拖动的时候
        if (this.timer) {
          clearTimeout(this.timer);
        }
        this.timer = setTimeout(() => {
          // 正在滑动的字母到顶部的距离减去头部的距离
          const touchY = e.touches[0].clientY - 79;
          // A字母到顶部的距离 浅蓝色下沿
          const startY = this.$refs["A"][0].offsetTop // 207
          // 移动中距离顶部的高度的减去第一个到顶部的高度 / 每个字母的高度
          const index = Math.floor((touchY - startY) / 20);
          if (index >= 0 && index < this.letters.length) {
            this.$emit("change", this.letters[index]); // A B C D
          }
        }, 8);
      }
    },
    handleTouchEnd() {
      this.touchStatus = false;
    },
  },
};
</script>

<style lang="stylus" scoped>
@import '@/assets/styles/varibles.styl'
.list
  display: flex
  flex-direction: column
  justify-content: center
  position: absolute
  top: 1.58rem
  right: 0
  bottom: 0
  width: .4rem
  .item
    line-height: .4rem
    text-align: center
    color: $bgColor
</style>
